package com.itouch.bracelet.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.R.color;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.adapter.MyAdapter;
import com.itouch.bracelet.bean.BaseResult;
import com.itouch.bracelet.bean.CircleInfo;
import com.itouch.bracelet.bean.CircleReply;
import com.itouch.bracelet.bean.CircleResult;
import com.itouch.bracelet.bean.CommentResult;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.itouch.util.JsonAndPhpUtil;
import com.itouch.util.LoadingDialog;
import com.itouch.widget.MyListView;
import com.itouch.widget.MyListView.startRefresh;
import com.itouch.widget.actionsheet.ActionSheet;
import com.itouch.widget.actionsheet.Method.Action1;

/**
 * 

* @ClassName: FriendCircleActivity 

* @Description: TODO(朋友圈) 

* @author sunshineHu hucx@itouch.com.cn

* @date 2015年1月21日 下午2:56:19 

*
 */
public class FriendCircleActivity extends SherlockFragmentActivity implements OnClickListener{

	private LoadingDialog loadingDialog;
	
	private ExecutorService es;
	private int page=1;
	private MyListView lv;
	private MyAdapter adapter;
	private CircleResult result;	
	
	private EditText comment;
	private TextView btn;
	private View rl1;
	
	private String blogId="";
	private String commentId="0";
	
	private int blogPos;
	
	private CircleReply lastReply;
	
	private String userId;
	
	private LinearLayout parent;
	
	@SuppressLint("HandlerLeak") private Handler mHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			case 0:
				disMiss();
				if(result==null){
					return;
				}
				if(result.getRows().size()==0){
					Toast.makeText(FriendCircleActivity.this, "没有更多数据了！", Toast.LENGTH_SHORT).show();
					lv.stopRefresh();
				}
				adapter.modifyData(result.getRows());
				adapter.notifyDataSetChanged();
				lv.stopLoadMore();
				if(result.getRows().size()<10){
					lv.setPullLoadEnable(false);
				}else{
					lv.setPullLoadEnable(true);
				}
				lv.stopRefresh();
				break;
			case 1:
				break;
			case 2:
				//点赞 
				String s=(String) msg.obj;
				blogId=s.substring(0, s.indexOf("&"));
				blogPos=Integer.valueOf(s.substring(s.indexOf("&")+1));
				es.execute(praiseThread);
				break;
			case 3:
				String ss=(String) msg.obj;
				blogId=ss.substring(0, ss.indexOf("&"));
				blogPos=Integer.valueOf(ss.substring(ss.indexOf("&")+1));
				commentId="0";
				loadInput();
				break;
			case 4:
				final ActionSheet actionSheet = new ActionSheet(FriendCircleActivity.this);
				lastReply=(CircleReply) msg.obj;
				blogId=lastReply.getFriendId();
				commentId=lastReply.getId();
				blogPos=lastReply.getBlogPos();
				actionSheet.show("",new String[]{"删除" },new Action1<Integer>(){
					@Override
					public void invoke(Integer index) {
						actionSheet.hide();
						if(index==0){
							es.execute(deleteThread);
						}
					}
				});
				break;
			case 5:
				lastReply=(CircleReply) msg.obj;
				blogId=lastReply.getFriendId();
				commentId=lastReply.getId();
				blogPos=lastReply.getBlogPos();
				loadInput();
				break;
			case 6:
				/*Toast.mak("回复成功！");
				new Thread(getList).start();
				lv.startCircleAnimation();
				BlogReply br=new BlogReply();
				br.setContent(comment.getText().toString());
				br.setName(app.getUserInfo().getName());
				mylist.get(Integer.valueOf(position)).getReplys().add(br);
				adapter.modifyData(mylist);
				adapter.notifyDataSetChanged();*/
				
				CommentResult re=(CommentResult) msg.obj;
				if(!re.isFlag()){
					Toast.makeText(FriendCircleActivity.this, re.getMsg(), Toast.LENGTH_SHORT).show();
					break;
				}
				if(commentId.equals("0")){
					//首级评论
					CircleReply reply1=new CircleReply();
					reply1.setUsername(UserCache.getOauth(FriendCircleActivity.this).getUserName());
					reply1.setContent(comment.getText().toString());
					reply1.setFlag("顶级回复");
					reply1.setCreator(UserCache.getOauth(FriendCircleActivity.this).getUserId());
					reply1.setId(re.getRows()+"");
					
					List<CircleReply> list = result.getRows().get(blogPos).getReplyInfo();
					if(list==null){
						list=new ArrayList<CircleReply>();
						result.getRows().get(blogPos).setReplyInfo(list);
					}
					list.add(reply1);
					
					adapter.notifyDataSetChanged();
				}else{
					//对评论进行评论
					CircleReply reply1=new CircleReply();
					reply1.setUsername(UserCache.getOauth(FriendCircleActivity.this).getUserName());
					reply1.setContent(comment.getText().toString());
					reply1.setFromUser(lastReply.getUsername());
					reply1.setFlag("");
					reply1.setCreator(UserCache.getOauth(FriendCircleActivity.this).getUserId());
					reply1.setId(re.getRows()+"");
					
					result.getRows().get(blogPos).getReplyInfo().add(lastReply.getCommentPos()+1,reply1);
					
					adapter.notifyDataSetChanged();
				}
				
				Toast.makeText(FriendCircleActivity.this, "回复成功！", Toast.LENGTH_SHORT).show();
				comment.setText("");
				rl1.setVisibility(View.GONE);
				((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(FriendCircleActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);   
				break;
			case 7:
				
				BaseResult res=(BaseResult) msg.obj;
				if(!res.isFlag()){
					Toast.makeText(FriendCircleActivity.this, res.getMsg(), Toast.LENGTH_SHORT).show();
					break;
				}
				
				if(result.getRows().get(blogPos).isPraiseFlag()){
					result.getRows().get(blogPos).setPraiseFlag(false);
					String names[]=result.getRows().get(blogPos).getPraiseUser().split(",");
					int len=names.length;
					for(int i=0;i<len;i++){
						if(names[i].equals(UserCache.getOauth(FriendCircleActivity.this).getUserName())){
							names[i]=null;
						}
					}
					String sss="";
					for(int i=0;i<len;i++){
						if(names[i]!=null){
							sss=sss+names[i];
						}
					}
					result.getRows().get(blogPos).setPraiseUser(sss);
				}else{
					result.getRows().get(blogPos).setPraiseFlag(true);
					String ssss=result.getRows().get(blogPos).getPraiseUser();
					if(ssss.equals("")){
						ssss=UserCache.getOauth(FriendCircleActivity.this).getUserName();
					}else{
						ssss=ssss+","+UserCache.getOauth(FriendCircleActivity.this).getUserName();
					}
						
					result.getRows().get(blogPos).setPraiseUser(ssss);
				}
				adapter.notifyDataSetChanged();
				break;
			case 8:
				BaseResult resu=(BaseResult) msg.obj;
				if(!resu.isFlag()){
					Toast.makeText(FriendCircleActivity.this, resu.getMsg(), Toast.LENGTH_SHORT).show();
					break;
				}
				result.getRows().get(blogPos).getReplyInfo().remove(lastReply.getCommentPos());
				adapter.notifyDataSetChanged();
				break;
			case 9:
				userId=(String) msg.obj;
				
				break;
			}
		}
		
	};
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		es=Executors.newSingleThreadExecutor();
		setContentView(R.layout.friend_circle_layout);
		if(getSupportActionBar()!=null){
			getSupportActionBar().hide();
		}
		
		parent=(LinearLayout) findViewById(R.id.parent);
		
		userId=UserCache.getOauth(FriendCircleActivity.this).getUserId();
		lv=new MyListView(this, new startRefresh() {
			
			@Override
			public void logoClick() {
				// TODO Auto-generated method stub
				/*userId=UserCache.getOauth(FriendCircleActivity.this).getUserId();
				page=1;
				es.execute(getList);*/
				
				/*点击头像跳转动作，暂时不跳转
				Intent in=new Intent(FriendCircleActivity.this, PersonCircleActivity.class);
				in.putExtra("id", UserCache.getOauth(FriendCircleActivity.this).getUserId());
				in.putExtra("logo", UserCache.getOauth(FriendCircleActivity.this).getPath());
				in.putExtra("name", UserCache.getOauth(FriendCircleActivity.this).getUserName());
				FriendCircleActivity.this.startActivity(in);
				*/
			}
			
			@Override
			public void loadMore() {
				// TODO Auto-generated method stub
				page++;
				show();
				es.execute(getList);
			}
			
			@Override
			public void loadData() {
				// TODO Auto-generated method stub
				page=1;
				es.execute(getList);
				
			}
		}, UserCache.getOauth(FriendCircleActivity.this).getUserName(), UserCache.getOauth(FriendCircleActivity.this).getPath());
		lv.setDivider(null);
		lv.setCacheColorHint(color.transparent);
		parent.addView(lv);
		lv.startCircleAnimation();
		
		adapter=new MyAdapter(new ArrayList<CircleInfo>(), FriendCircleActivity.this, mHandler);
		lv.setAdapter(adapter);
		
		ImageView add=(ImageView) findViewById(R.id.add);
		add.setOnClickListener(this);
		
		loadbottom();
		
		
		show();
		es.execute(getList);
	}

	
	private void loadbottom(){
		
		rl1=findViewById(R.id.bottom);
		rl1.setVisibility(View.GONE);
		
	}
	
	
	
	private void loadInput(){
		
		rl1.setVisibility(View.VISIBLE);
		comment=(EditText) rl1.findViewById(R.id.et_sendmessage);
		btn=(TextView) rl1.findViewById(R.id.btn_send);
		comment.setFocusable(true);
		comment.setFocusableInTouchMode(true);
		comment.requestFocus();
		InputMethodManager inputManager =
                    (InputMethodManager)comment.getContext().getSystemService(FriendCircleActivity.this.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(comment, 0);
        btn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(!comment.getText().toString().equals("")){
					es.execute(commentThread);
				}else{
					Toast.makeText(FriendCircleActivity.this, "评论内容不能为空！", Toast.LENGTH_SHORT).show();
				}
				
			}
		});
	}
	
	
	
	
	
	private Runnable getList=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			List<NameValuePair> lists = new ArrayList<NameValuePair>();
			lists.add(new BasicNameValuePair("rows", "10"));
			lists.add(new BasicNameValuePair("page", page+""));
			lists.add(new BasicNameValuePair("filter_S_id", userId));
			//lists.add(new BasicNameValuePair("filter_S_id", "17"));
			String ss = JsonAndPhpUtil.postHttpData(Constants.URL+"/mobi/friendCircle/list",lists, FriendCircleActivity.this);	
			result=new Gson().fromJson(ss, CircleResult.class);
			Message msg=mHandler.obtainMessage(0);
			msg.sendToTarget();
		}
	};
	
	
	private Runnable commentThread=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			List<NameValuePair> lists = new ArrayList<NameValuePair>();
			lists.add(new BasicNameValuePair("friendId", blogId));
			lists.add(new BasicNameValuePair("creator", UserCache.getOauth(FriendCircleActivity.this).getUserId()));
			lists.add(new BasicNameValuePair("content", comment.getText().toString()));
			lists.add(new BasicNameValuePair("userid", commentId));
			lists.add(new BasicNameValuePair("mark", "0"));
			lists.add(new BasicNameValuePair("username",UserCache.getOauth(FriendCircleActivity.this).getUserName()));
			String ss = JsonAndPhpUtil.postHttpData(Constants.URL+"/handchain/mobi/friendCircle/insertDiscuss",lists, FriendCircleActivity.this);	
			CommentResult result=new Gson().fromJson(ss, CommentResult.class);
			Message msg=mHandler.obtainMessage(6);
			msg.obj=result;
			msg.sendToTarget();
		}
	};
	
	
	private Runnable praiseThread=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			List<NameValuePair> lists = new ArrayList<NameValuePair>();
			lists.add(new BasicNameValuePair("friendId", blogId));
			lists.add(new BasicNameValuePair("creator", UserCache.getOauth(FriendCircleActivity.this).getUserId()));
			//lists.add(new BasicNameValuePair("filter_S_id", UserCache.getOauth(FriendCircleActivity.this).getUserId()));
			String ss = JsonAndPhpUtil.postHttpData(Constants.URL+"/handchain/mobi/friendCircle/praise",lists, FriendCircleActivity.this);	
			BaseResult result=new Gson().fromJson(ss, BaseResult.class);
			Message msg=mHandler.obtainMessage(7);
			msg.obj=result;
			msg.sendToTarget();
		}
	};

	
	private Runnable deleteThread=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			List<NameValuePair> lists = new ArrayList<NameValuePair>();
			lists.add(new BasicNameValuePair("id", blogId));
			lists.add(new BasicNameValuePair("creator", UserCache.getOauth(FriendCircleActivity.this).getUserId()));
			//lists.add(new BasicNameValuePair("filter_S_id", UserCache.getOauth(FriendCircleActivity.this).getUserId()));
			String ss = JsonAndPhpUtil.postHttpData(Constants.URL+"/handchain/mobi/friendCircle/deleteReplyByOneself",lists, FriendCircleActivity.this);	
			BaseResult result=new Gson().fromJson(ss, BaseResult.class);
			Message msg=mHandler.obtainMessage(8);
			msg.obj=result;
			msg.sendToTarget();
		}
	};



	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.add:
			Intent in=new Intent(FriendCircleActivity.this, FriendCircleAddActivity.class);
			startActivityForResult(in, 123);
			break;
		}
	}
	
	
	
	/**
	 * 显示进度加载
	 */
	public void show() {
		if (loadingDialog == null) {
			loadingDialog = LoadingDialog.createDialog(this);
			// 点击外部区域，是否消失loadingDialog
			loadingDialog.setCanceledOnTouchOutside(false);
		}
		loadingDialog.setMessage("正在加载");
		loadingDialog.show();
	}

	/**
	 * 关闭进度加载
	 */
	public void disMiss() {
		if (loadingDialog != null) {
			loadingDialog.dismiss();
			loadingDialog = null;
		}
	}

	
	public void back(View v){
		finish();
	}


	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if(arg0==123&&arg1==RESULT_OK){
			
			show();
			page=1;
			new Thread(getList).start();
			
		}
	}
	
	
	
	
	
}
